package com.lx.boot.web.convert;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.lx.annotation.Note;
import com.lx.boot.OS;
import com.lx.boot.web.convert.serializer.SerializerHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import java.util.List;

@Slf4j
@AutoConfiguration
public class ConvertUtils implements CommandLineRunner {

    private static ObjectMapper objectMapper = OS.getBean(ObjectMapper.class);

    @Override
    public void run(String... args) throws Exception {
        // null值时也由处理器处理
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new BeanSerializerModifier(){
            @Override
            public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
                for (BeanPropertyWriter writer : beanProperties) {
                    if (writer.getSerializer() instanceof SerializerHandler serializer) {
                        writer.assignNullSerializer(serializer);
                    }
                }
                return beanProperties;
            }
        }));
    }

    @Note("转换对象信息")
    public static  <T> T convert(T t){
        return (T) objectMapper.convertValue(t,t.getClass());
    }

    @Note("转换对象信息")
    public static  <T> T convert(String json,Class<T> tClass){
        return (T) objectMapper.convertValue(json,tClass);
    }
}
